<?php

class Core_View_Helper_MenuBuilder extends Zend_View_Helper_Abstract
{

	private $_isFirst   = true;
    private $_sort      = '';

	public function __construct()
	{
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $this->_sort = $request->getParam('sort','latest_products');
	}

	/**
	 *
	 * @param array $list
	 * @return string 
	 */
	public function menuBuilder(array $list, $currentRootCategory = '', $parent_name = 'root', $parentUrl = '', $isFirstLevel = true, $isAddOther = true)
	{
		if ($this->_isFirst)
		{
			$html = '<ul class="sf-menu">' . PHP_EOL;
			$this->_isFirst = false;
		}
		else
		{
			$html = '<ul>' . PHP_EOL;
		}

		$categories = explode('-', $currentRootCategory);

		if (sizeof($categories) >= 2)
		{
			$currentRootCategory = $categories[0] . '-%';
		}
		$_isAddOther = true;
		foreach ($list as $category)
		{
			if ($category['path'] . '%' == $currentRootCategory)
			{
				$html .= '<li class="current smHover">' . PHP_EOL;
			}
			else
			{
				$html .= '<li class="current">' . PHP_EOL;
			}
			if(intval($category['number_active_products'])>0)
			{
				$_isAddOther = true;
			}
			else
			{
				$_isAddOther = false;
			}
			
			$url = $this->view->pageUrl(array('module' => 'tab', 'target' => 'index', 'id_category' => $category['path'] . '%'), true);
			$html .= sprintf('<a href="%s">%s</a>', $url, $category['name']) . PHP_EOL;

			if (array_key_exists('children', $category))
			{
				$html .= $this->menuBuilder($category['children'], $currentRootCategory, $category['name'], $url, false, $_isAddOther);
			}

			$html .= '</li>' . PHP_EOL;
		}

		if (!$isFirstLevel && $isAddOther)
		{
			$html .= '<li>' . PHP_EOL;
			//remove % in the end of category id_category/1-25-% --> id_category/1-25-
			$html .= sprintf('<a href="%s">%s</a>', str_replace('%25', '', $parentUrl), $this->view->translate('Other')) . PHP_EOL;
			$html .= '</li>';
		}

		$html .= '</ul>' . PHP_EOL;
		return $html;
	}

}